import React, { createContext, useState, useContext, ReactNode } from 'react';
import { IStudent, IStudentContext } from '../../types';

// 创建初始学生数据
const initialStudents: IStudent[] = [
  {
    id: '1',
    name: '张三',
    gender: '男',
    studentId: '2021001',
    grade: '高一',
    class: '1班'
  },
  {
    id: '2',
    name: '李四',
    gender: '女',
    studentId: '2021002',
    grade: '高二',
    class: '2班'
  },
  {
    id: '3',
    name: '王五',
    gender: '男',
    studentId: '2021003',
    grade: '高三',
    class: '3班'
  },
  {
    id: '4',
    name: '赵六',
    gender: '女',
    studentId: '2021004',
    grade: '高一',
    class: '1班'
  },
  {
    id: '5',
    name: '钱七',
    gender: '男',
    studentId: '2021005',
    grade: '高二',
    class: '2班'
  }
];

// 创建 Context
const StudentContext = createContext<IStudentContext | undefined>(undefined);

// 创建 Provider 组件
export const StudentProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [students, setStudents] = useState<IStudent[]>(initialStudents);
  const [filters, setFilters] = useState({
    name: '',
    gender: '',
    studentId: ''
  });

  // 添加学生
  const addStudent = (student: Omit<IStudent, 'id'>) => {
    const newStudent = {
      ...student,
      id: Date.now().toString()
    };
    setStudents([...students, newStudent]);
  };

  // 更新学生信息
  const updateStudent = (id: string, updatedStudent: Partial<IStudent>) => {
    setStudents(
      students.map(student => 
        student.id === id ? { ...student, ...updatedStudent } : student
      )
    );
  };

  // 删除学生
  const deleteStudent = (id: string) => {
    setStudents(students.filter(student => student.id !== id));
  };

  // 根据筛选条件过滤学生
  const filteredStudents = students.filter(student => {
    return (
      (filters.name === '' || student.name.includes(filters.name)) &&
      (filters.gender === '' || student.gender === filters.gender) &&
      (filters.studentId === '' || student.studentId === filters.studentId)
    );
  });

  const value = {
    students,
    addStudent,
    updateStudent,
    deleteStudent,
    filteredStudents,
    setFilters
  };

  return (
    <StudentContext.Provider value={value}>
      {children}
    </StudentContext.Provider>
  );
};

// 创建自定义 hook 以便在组件中使用 context
export const useStudents = () => {
  const context = useContext(StudentContext);
  if (context === undefined) {
    throw new Error('useStudents must be used within a StudentProvider');
  }
  return context;
};